package com.cn.kehong.service;


import com.cn.kehong.api.IDbBackService;
import com.cn.kehong.conf.Config;
import com.cn.kehong.dao.DbBackMapper;
import com.cn.kehong.domain.DbBack;
import com.cn.kehong.domain.DbBackExample;
import com.cn.kehong.utils.CollectionsUtil;
import com.cn.kehong.utils.CommonUtil;
import com.cn.kehong.utils.Constants;
import com.cn.kehong.utils.QueryForm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@EnableScheduling
@Service
public class DbBackServiceImpl implements IDbBackService {


    @Autowired
    private DbBackMapper dbBackMapper;

    @Autowired
    private Config config;


    private static boolean release = true;

    @Override
    public List<DbBack> queryDbBackList(QueryForm queryForm) throws Exception {
        DbBackExample example  = new DbBackExample();
        DbBackExample.Criteria criteria = example.createCriteria();
        criteria.andStatusEqualTo(Constants.NORMAL_STATUS);
        if(StringUtils.isNotBlank(queryForm.getName())){
            criteria.andBackNameEqualTo(queryForm.getName());
        }
        List<DbBack> list = dbBackMapper.selectByExample(example);
        for(DbBack dbBack:list){
            String fileSize = dbBack.getBackSize();
            if(StringUtils.isNotEmpty(fileSize)){
                int size = Integer.parseInt(fileSize);
                size = size/1024;
                dbBack.setBackSize(size+"");
            }
        }
        return list;
    }

    @Override
    public String deleteDbBack(QueryForm queryForm) throws Exception {
        List<String> ids = queryForm.getIds();
        if(CollectionsUtil.isEmpty(ids)){
            throw new Exception("deleteDtcDbBack ids 为空！");
        }
        DbBackExample example  = new DbBackExample();
        example.createCriteria().andIdIn(ids);
        DbBack update = new DbBack();
        update.setStatus(Constants.DEL_STATUS);
        int count = dbBackMapper.updateByExampleSelective(update,example);
        return  CommonUtil.outStr(count);
    }

    @Override
    public String addDbBack(DbBack dbBack) throws Exception {
        dbBack.setId(CommonUtil.generateRandomNum("db-"));
        int count = dbBackMapper.insertSelective(dbBack);
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateDbBack(DbBack dbBack) throws Exception {
        return null;
    }

    @Scheduled(cron = "0 0 23 * * ?")
//    @Scheduled(cron = "*/5 * * * * ?")
    public void backDb() throws Exception{
        Runtime runtime = Runtime.getRuntime();
        InputStream inputStream = null;
        InputStreamReader reader = null;
        FileOutputStream fileOutputStream = null;
        String dbStatus = "1";
        String path = "";
        if(!release){
            return;
        }
        release = false;
        BufferedReader br = null;
        Process process = runtime.exec(" mysqldump -R --port=3306"+" -h" +"localhost" +
                " -p"+config.password+" -u" + config.username+ " --set-charset="+"UTF-8&"+" " + "device_bxh");
        SimpleDateFormat dateFormater1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String fileName = "";
        try {
            SimpleDateFormat dateFormater = new SimpleDateFormat("yyyyMMdd");
            Date date=new Date();
            String sqlDate= dateFormater.format(date);
            File file = new File(config.dbPath);
            fileName = sqlDate+".sql";
            File realfile=new File(file,sqlDate+".sql");
            path = config.dbPath +sqlDate+".sql";
            if  (!file .exists()  && !file .isDirectory())
            {
                file.mkdirs();
            }
            inputStream = process.getInputStream();
            reader= new InputStreamReader(inputStream,"utf-8");
            br = new BufferedReader(reader);
            StringBuffer sb = new StringBuffer();
            String s = null;
            while((s = br.readLine()) != null){
                sb.append(s+"\r\n");
            }
            s = sb.toString();
            fileOutputStream = new FileOutputStream(realfile);
            fileOutputStream.write(s.getBytes());
            fileOutputStream.close();
            br.close();
            reader.close();
            inputStream.close();
        }catch (Exception e){
            dbStatus = "2";
        }finally {
            release = true;
            DbBack dbBack = new DbBack();
            dbBack.setBackStatus(dbStatus);
            dbBack.setBackPath(path);
            dbBack.setBackName(fileName);
            dbBack.setBackTime(dateFormater1.format(new Date()));
            File file = new File(dbBack.getBackPath());
            if (!file.exists() || !file.isFile()) {
                throw new RuntimeException("文件不存在");
            }
            String size = file.length()  + "";
            dbBack.setBackSize(size);
            this.addDbBack(dbBack);
            try {
                if (null != fileOutputStream)
                {
                    fileOutputStream.close();
                }
                if (null != br)
                {
                    br.close();
                }
                if (null != reader)
                {
                    reader.close();
                }
                if (null != inputStream)
                {
                    inputStream.close();
                }
            } catch (IOException e) {
                throw new RuntimeException("关闭失败");
            }
        }
    }
}
